package com.century.sjt.activity.Pay;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allinpay.appayassistex.APPayAssistEx;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.SjtHelper;
import com.century.sjt.EMChat.activity.ChatActivity;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.entity.Merchant;
import com.century.sjt.fragment.MerchantItemInfoFragment;
import com.century.sjt.fragment.MerchantItemPayFragment;
import com.century.sjt.util.Constant;
import com.century.sjt.util.MyViewPager;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;
import com.century.sjt.EMChat.domain.EaseUser;
import com.century.sjt.EMChat.utils.EaseCommonUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商家信息
 */
public class MerchantItemActivity extends BaseActivity {

    private Handler mHandler;
    private RequestQueue mQueue;
    private MyViewPager mViewPager;
    private FragmentPagerAdapter mAdapter;
    private List<Fragment> mDatas;

    private TextView mMessageTextView;
    private TextView mWaitingToPayTextView;
    private TextView mFriendTextView;
    private LinearLayout mChatLinearLayout;
    //private BadgeView mBadgeView;
    private Fragment[] fragments;
    private ImageView mTabline,mTabline2;
    private int mScreen1_3;
    MerchantItemInfoFragment tab01 = new MerchantItemInfoFragment();
    MerchantItemPayFragment tab02 = new MerchantItemPayFragment();
    private String payType;
    private int mCurrentPageIndex;
    private Merchant aMerchant;

    private LinearLayout mTab1, mTab2, mTab3;

    private SjtTitleBar titleBar;
    private String shopId;
    private List<EaseUser> users = new ArrayList<>() ;

    private String isShop,isMerchant;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.sjt_merchant_top);
        mQueue = Volley.newRequestQueue(this);

        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);

        //       标题栏
        titleBar.setTitle(getResources().getString(R.string.tab_merchant_item));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        Intent intent = getIntent();

        payType=intent.getStringExtra("payType");
        aMerchant=(Merchant)intent.getSerializableExtra("Merchant");
//        if (payType.equals("0")){
//            shopId = intent.getStringExtra("shopId");
////            shopDetail(shopId);
////            Bundle data = new Bundle();
////            data.putSerializable("Merchant", getaMerchant());
////            tab01.setArguments(data);//通过Bundle向Activity中传递值
////            tab01.setArguments(data);//通过Bundle向Activity中传递值
//        }else {
//            aMerchant=(Merchant)intent.getSerializableExtra("Merchant");
//        }


        initTabLine();
        initView();
        if (payType.equals("2")){
            resetTextView();
            mWaitingToPayTextView.setTextColor(getResources().getColor(R.color.textdefault_title));
//            mTabline.setVisibility(View.INVISIBLE);
//            mTabline2.setVisibility(View.VISIBLE);
            mViewPager.setCurrentItem(1);
        }else {
            resetTextView();
            mFriendTextView.setTextColor(getResources().getColor(R.color.textdefault_title));
//            mTabline.setVisibility(View.VISIBLE);
//            mTabline2.setVisibility(View.INVISIBLE);
        }
        titleBar.setTitle(getResources().getString(R.string.tab_merchant_details));
}

    public Merchant getaMerchant() {
        return aMerchant;
    }

    public void setaMerchant(Merchant aMerchant) {
        this.aMerchant = aMerchant;
    }

    private void initTabLine() {
        mTabline = (ImageView) findViewById(R.id.id_iv_tabline);
//        mTabline2=(ImageView)findViewById(R.id.id_iv_tabline2);
        Display display = getWindow().getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);
        mScreen1_3 = outMetrics.widthPixels / 3;
        ViewGroup.LayoutParams lp = mTabline.getLayoutParams();
        lp.width = mScreen1_3;
        mTabline.setLayoutParams(lp);
    }
    @Override
    protected void initView() {
        SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        isShop = mainSharedPreferences.getString("isShop", "");
        isMerchant = mainSharedPreferences.getString("isMerchant","");


        mViewPager = (MyViewPager) findViewById(R.id.aviewpager);
//        mViewPager.setScrollble(false);
        mMessageTextView=(TextView)findViewById(R.id.id_tv_chat);
        mWaitingToPayTextView = (TextView) findViewById(R.id.id_tv_pay);
        mFriendTextView = (TextView) findViewById(R.id.id_tv_friend);

        mTab1 =(LinearLayout)findViewById(R.id.id_ll_tab1);
        mTab2 = (LinearLayout) findViewById(R.id.id_ll_tab2);
        mTab3 = (LinearLayout) findViewById(R.id.id_ll_tab3);

        mDatas = new ArrayList<Fragment>();

        //Fragement界面
//        MerchantItemInfoFragment tab01 = new MerchantItemInfoFragment();
//        MerchantItemPayFragment tab02 = new MerchantItemPayFragment();

//        MerchantMessageFragment tab03 =new MerchantMessageFragment();
        mDatas.add(tab01);
        mDatas.add(tab02);
//        mDatas.add(tab03);

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return mDatas.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return mDatas.get(arg0);
            }
        };

        mViewPager.setAdapter(mAdapter);
        mTab1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetTextView();
                mFriendTextView.setTextColor(getResources().getColor(R.color.textdefault_title));
//                mTabline.setVisibility(View.VISIBLE);
//                mTabline2.setVisibility(View.INVISIBLE);
                mViewPager.setCurrentItem(0);

            }
        });

        mTab2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(isMerchant)||"1".equals(isShop)){
                    showAppayRes();
                }else {
                    resetTextView();
                    mWaitingToPayTextView.setTextColor(getResources().getColor(R.color.textdefault_title));
//                mTabline.setVisibility(View.INVISIBLE);
//                mTabline2.setVisibility(View.VISIBLE);
                    mViewPager.setCurrentItem(1);
                }
            }
        });

        mTab3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(isMerchant)||"1".equals(isShop)){
                    showAppayRes();
                }else {
                    if (SjtHelper.getInstance().getContactList().get(aMerchant.getUserId())==null){
                        AddShop(aMerchant.getUserId());
                    }else {
                        startActivity(new Intent(MerchantItemActivity.this, ChatActivity.class).putExtra("userId",aMerchant.getUserId()));
                    }
                }


            }
        });



        intoVP();

    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData() {

    }

    private void intoVP() {
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                resetTextView();
                switch (position) {
                    case 0:
                        mFriendTextView.setTextColor(getResources().getColor(R.color.textdefault_title));
                        break;
                    case 1:
                        if ("1".equals(isMerchant)||"1".equals(isShop)){
                            showAppayRes();
                            mWaitingToPayTextView.setTextColor(getResources().getColor(R.color.textdefault_title));
                        }else {
                            mWaitingToPayTextView.setTextColor(getResources().getColor(R.color.textdefault_title));
                        }
                        break;
//                    case 2:
//                        mMessageTextView.setTextColor(getResources().getColor(R.color.black));
//                        break;
                }

                mCurrentPageIndex = position;

            }


            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPx) {
//                Log.e("TAG", position + " , " + positionOffset + " , "
//                        + positionOffsetPx);

                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTabline
                        .getLayoutParams();

                if (mCurrentPageIndex == 0 && position == 0)// 0->1
                {
                    lp.leftMargin = (int) (positionOffset * mScreen1_3 + mCurrentPageIndex
                            * mScreen1_3);
                } else if (mCurrentPageIndex == 1 && position == 0)// 1->0
                {
                    lp.leftMargin = (int) (mCurrentPageIndex * mScreen1_3 + (positionOffset - 1)
                            * mScreen1_3);
                } else if (mCurrentPageIndex == 1 && position == 1) // 1->2
                {
                    lp.leftMargin = (int) (mCurrentPageIndex * mScreen1_3 + positionOffset
                            * mScreen1_3);
                } else if (mCurrentPageIndex == 2 && position == 1) // 2->1
                {
                    lp.leftMargin = (int) (mCurrentPageIndex * mScreen1_3 + ( positionOffset-1)
                            * mScreen1_3);
                }
                mTabline.setLayoutParams(lp);

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    protected void resetTextView() {

        mFriendTextView.setTextColor(getResources().getColor(R.color.textdefault_title));

        mWaitingToPayTextView.setTextColor(getResources().getColor(R.color.textdefault_title));

        mMessageTextView.setTextColor(getResources().getColor(R.color.textdefault_title));
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (APPayAssistEx.REQUESTCODE == requestCode) {
            if (null != data) {
                String payRes = null;
                String payAmount = null;
                String payTime = null;
                String payOrderId = null;
                try {
                    JSONObject resultJson = new JSONObject(data.getExtras().getString("result"));
                    payRes = resultJson.getString(APPayAssistEx.KEY_PAY_RES);
                    payAmount = resultJson.getString("payAmount");
                    payTime = resultJson.getString("payTime");
                    payOrderId = resultJson.getString("payOrderId");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (null != payRes && payRes.equals(APPayAssistEx.RES_SUCCESS)) {
//                    Intent intent = new Intent();
//                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    intent.putExtra("payType", "2");
//                    intent.setClass(MerchantItemActivity.this, MerchantActivity.class);
//                    startActivity(intent);
                    startActivity(new Intent(MerchantItemActivity.this, ChatActivity.class).putExtra("userId",aMerchant.getUserId()));

//                    Timer timer = new Timer();
//                    TimerTask tast = new TimerTask() {
//                        @Override
//                        public void run() {
//                            startActivity(new Intent(MerchantItemActivity.this, ChatActivity.class).putExtra("userId",aMerchant.getUserId()));
//                        }
//                    };
//                    timer.schedule(tast, 400);
//                    showAppayRes("支付成功！");
//                    if (SjtHelper.getInstance().getContactList().get(aMerchant.getUserId())==null){
//                        SjtHelper.getInstance().updateFetchContacts();
//                    }
                }else {
//                    showAppayRes("支付失败！");
                    consumeCancel(tab02.getOrderNo());
                    TipUtil.showToast(getResources().getString(R.string.error_pay_no), MerchantItemActivity.this, 1);

                }
                Log.d("payResult", "payRes: " + payRes + "  payAmount: " + payAmount + "  payTime: " + payTime + "  payOrderId: " + payOrderId);
            }
        }
    }
    public void showAppayRes(final String res) {
        new AlertDialog.Builder(this)
                .setMessage(res)
                .setTitle(getResources().getString(R.string.text_prompt))
                .setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (res.equals(getResources().getString(R.string.error_pay_ok))){
                            Intent intent = new Intent();
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            intent.putExtra("payType", "2");
                            intent.setClass(MerchantItemActivity.this, MerchantActivity.class);
                            startActivity(intent);

                        }else {
                            Log.e("OrderNo", tab02.getOrderNo());
                            consumeCancel(tab02.getOrderNo());
                        }

                    }
                })
                .show();
    }

    private void consumeCancel(final String orderNo) {
        //显示Progress Dialog
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.GetConsumeCancel, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        Log.e("depositCancel","订单取消成功");
//                        Log.e("text", Data.getString("issuerId") + "&" + Data.getString("tradeNature"));


                    } else {//失败
//                        TipUtil.showToast(message, WalletRechareActivity.this, 1);
                        TipUtil.log("订单取消失败！", message.toString(), 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
//                    TipUtil.showToast(getResources().getString(R.string.error_service), WalletRechareActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                TipUtil.showToast(getResources().getString(R.string.error_network), WalletRechareActivity.this, 1);
//                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("orderNo",orderNo);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

    private void shopDetail(final String shopId) {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), MerchantItemActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.ShopDetail, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONObject aData = res.getJSONObject("data");
                        Merchant merchant = new Merchant();
                        merchant.setShopId(aData.getString("shopId"));
                        merchant.setShopName(aData.getString("shopName"));
//                            Log.e("name",aData.getString("shopName"));
                        merchant.setLogo(aData.getString("logo"));
                        merchant.setDiscount(aData.getString("discount"));
                        merchant.setAddress(aData.getString("address"));
                        merchant.setTelephone(aData.getString("telephone"));
                        merchant.setTelephoneOne(aData.getString("telephoneOne"));
                        merchant.setMobile(aData.getString("mobile"));
                        merchant.setDesc(aData.getString("desc"));
                        merchant.setCity(aData.getString("city"));
                        merchant.setImage(aData.getString("image"));
                        merchant.setUserId(aData.getString("userId"));
                        setaMerchant(merchant);
                        initView();
                    } else {//失败
                        TipUtil.showToast(message, MerchantItemActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), MerchantItemActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), MerchantItemActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
                map.put("shopId",shopId);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }


    private void AddShop(final String friendId) {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), MerchantItemActivity.this);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.addFriendIsShop, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject Data= res.getJSONObject("data");
                    if (code.equals("200")) {//成功
                        JSONObject aData = Data.getJSONObject("friendShop");
                            String userId = aData.getString("userId");
                            String nick = aData.getString("nickName");
                            String initialLetter = aData.getString("initialLetter");
                            String mobile = aData.getString("mobile");
                            String imageId = aData.getString("imageId");
                            String imageUrl = aData.getString("imageUrl");
                            String Shopid = aData.getString("shopId");
                            EaseUser user = new EaseUser(userId);
                            user.setNick(nick);
                            user.setMobile(mobile);
                            user.setInitialLetter(initialLetter);
                            user.setAvatarid(imageId);
                            user.setAvatar(imageUrl);
                            user.setShopId(Shopid);
                            user.setIsShop("1");
                            EaseCommonUtils.setUserInitialLetter(user);
                            SjtHelper.getInstance().updateUser(user);
                        startActivity(new Intent(MerchantItemActivity.this, ChatActivity.class).putExtra("userId",friendId));

                    } else {//失败
                        new AlertDialog.Builder(MerchantItemActivity.this)
                                .setMessage(message)
                                .setTitle(getResources().getString(R.string.text_prompt))
                                .setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .show();
//                        TipUtil.showToast(message, MerchantItemActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), MerchantItemActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), MerchantItemActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("userId", userId);
                map.put("friendId",friendId);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }


    public void showAppayRes() {
        //询问是否取消
        AlertDialog.Builder builder = new AlertDialog.Builder(MerchantItemActivity.this);
        builder.setTitle(getResources().getString(R.string.text_prompt));
        builder.setMessage(getResources().getString(R.string.error_isshop_isno_pay));
        builder.setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                resetTextView();
                mFriendTextView.setTextColor(getResources().getColor(R.color.textdefault));
//                mTabline.setVisibility(View.VISIBLE);
//                mTabline2.setVisibility(View.INVISIBLE);
                mViewPager.setCurrentItem(0);
            }
        });
        builder.setCancelable(false);
        builder.create().show();
    }
}
